<template>
    <!-- 订单页面：使用el-row组件来布局，设置内边距、宽度，并居中对齐内容 -->
    <el-row style="padding: 2%;width: 100%;" justify="center" align="middle">
        <!-- 使用el-col组件，占24栅格宽度 -->
        <el-col :span="24">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/' }">饱了吗校园外卖平台</el-breadcrumb-item>
                <el-breadcrumb-item>
                    订单信息
                </el-breadcrumb-item>
            </el-breadcrumb>
        </el-col>
        <!-- 使用el-col组件，占20栅格宽度，显示一个标题分隔符 -->
        <el-col :span="20">
            <el-divider content-position="center">
                <el-text style="font-size: x-large;font-weight: bold;">
                    订单
                </el-text>
            </el-divider>
        </el-col>
        <!-- 使用el-col组件，占15栅格宽度，显示个人信息标题分隔符 -->
        <el-col :span="15" style="margin-top: 2%;">
            <el-divider content-position="center">
                <!-- 显示"个人信息"标题，设置字体大小和加粗 -->
                <el-text style="font-size: large;font-weight: bold;">
                    个人信息
                </el-text>
            </el-divider>
        </el-col>
        <!-- 使用el-col组件，占15栅格宽度，显示用户订单信息的表单 -->
        <el-col :span="15">
            <el-form ref="ruleFormRef" :model="ruleForm">
                <el-form-item label="创建时间：">
                    <el-text>{{ order?.create_time }}</el-text>
                </el-form-item>
                <el-form-item label="用户名称：">{{ user?.username }}</el-form-item>
                <el-form-item v-model="ruleForm.user" label="用户UID：">{{ user?.id }}</el-form-item>
                <el-form-item label="手机号码：">{{ user?.phone }}</el-form-item>
                <el-form-item label="订单状态：">待支付</el-form-item>
                <el-form-item v-model="ruleForm.address" label="收货地址：">{{
                    `${address?.school_name + address?.campus! + address?.address}` }}</el-form-item>
            </el-form>
        </el-col>
        <!-- 使用el-col组件，占15栅格宽度，显示外卖信息的标题分隔符 -->
        <el-col :span="15">
            <el-divider content-position="center">
                <!-- 显示"外卖信息"标题，设置字体大小和加粗 -->
                <el-text style="font-size: large;font-weight: bold;">
                    外卖信息
                </el-text>
            </el-divider>
            <!-- 显示外卖信息的表单 -->
            <el-form ref="ruleFormRef" :model="ruleForm">
                <el-form-item label="商品图片">
                    <el-image style="width: 200px;" :src="url"></el-image>
                </el-form-item>
                <el-form-item label="外卖编号：">{{ takeout?.id }}</el-form-item>
                <el-form-item label="外卖名称：">{{ takeout?.takeout_name }}</el-form-item>
                <el-form-item label="外卖类型：">{{ takeout?.kind }}</el-form-item>
                <el-form-item label="外卖状态：">正常</el-form-item>
                <el-form-item label="单品售价：">¥ {{ takeout?.price }}</el-form-item>
                <el-form-item label="购买数量：">{{ count }}</el-form-item>
                <el-form-item label="应付款：">¥ {{ price }}</el-form-item>
                <el-form-item label="支付方式：">
                    <el-radio-group v-model="payment" size="large">
                        <el-radio-button label="支付宝支付" value=1 />
                        <el-radio-button label="微信支付" value=0 />
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注：">
                    <el-input v-model="note" style="width: 100%" :rows="6" type="textarea" placeholder="你想对商家说：" />
                </el-form-item>
            </el-form>
        </el-col>
        <!-- 使用el-col组件，占24栅格宽度，显示提交按钮 -->
        <el-col :span="24" style="margin-bottom: 5%;">
            <el-row style="padding: 2%;width: 100%;" justify="center" align="middle">
                <!-- 提交按钮，按钮文字由status变量决定，点击时调用submitForm方法 -->
                <el-button type="warning" plain style="width: 50%;padding: 2%;" @click="submitForm">{{ status
                    }}</el-button>
            </el-row>
        </el-col>
    </el-row>

</template>

<script lang="ts" setup>
// 订单页面组件
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import { userInfoStore } from '../assets/userStore/userStore.ts';
import { ElMessage, FormInstance } from 'element-plus';

// 引入各种模型和API服务
import { UserModel } from '../assets/models/User.ts';
import { TakeoutModel } from '../assets/models/Takeout.ts';
import { OrderModel } from '../assets/models/Order.ts';
import { takeoutApis } from '../assets/apis/TakeoutApis.ts';
import { addressApis } from '../assets/apis/AddressApis.ts';
import { AddressModel } from '../assets/models/Address.ts';
import { userApis } from '../assets/apis/UserApis.ts';
import { orderApis } from '../assets/apis/OrderApis.ts';
import { paymentApis } from '../assets/apis/PaymentApis.ts';
import { PaymentModel } from '../assets/models/Payment.ts';
import { menuApis } from '../assets/apis/MenuApis.ts';


// 初始化状态
const userStore = userInfoStore(); // 初始化用户信息存储 
const router = useRouter(); // 获取路由实例  
const route = useRoute(); // 获取当前路由信息  
const takeout = ref<TakeoutModel>(); // 响应式引用，用于存储外卖信息  
const url = ref<string>(); // 响应式引用，用于存储图片URL  
const user = ref<UserModel>(); // 响应式引用，用于存储用户信息  
const count = ref<number>(); // 响应式引用，用于存储订单商品数量  
const price = ref<number>(); // 响应式引用，用于存储订单总价  
const order = ref<OrderModel>(); // 响应式引用，用于存储订单信息  
const address = ref<AddressModel>(); // 响应式引用，用于存储地址信息  
const status = ref<string>('提交订单'); // 响应式引用，用于存储订单状态描述 
const cstatus = ref<number>(0); // 响应式引用，用于标识订单状态（0: 新订单，1: 已提交待支付） 
const note = ref<string>(''); // 响应式引用，用于存储订单备注  
const payment = ref<number>(0); // 响应式引用，用于存储支付方式ID  
const takeout_id = ref<number>(); // 响应式引用，用于存储外卖ID  
const ruleFormRef = ref<FormInstance>(); // 响应式引用，用于存储表单实例（未使用） 
const ruleForm = reactive<OrderModel>({ // 响应式对象，用于存储订单表单数据
    user: userStore.id,
    takeout: 0,
    payment_method: 0,
    price: 0,
    count: 0,
    store: '',
    address: 0,
    note: '',
});

// 组件挂载时执行
onMounted(() => {
    // 从路由参数中获取外卖ID，并设置到表单和响应式引用中 
    takeout_id.value = Number(route.query.id);
    ruleForm.id = takeout_id.value;
    takeoutApis.queryTakeout(takeout_id.value)
        .then((value: TakeoutModel) => {
            takeout.value = value;
            url.value = `${value.takeout_portrait}`;
        })
    // 获取默认地址并设置到表单和响应式引用中
    addressApis.queryDefaultAddress(userStore.id)
        .then((value: AddressModel | undefined) => {
            address.value = value;
            ruleForm.address = value?.id!;
        })

    // 获取用户信息并设置到响应式引用中
    userApis.queryUser(userStore.id)
        .then((value: UserModel) => {
            user.value = value;
        })
    // 从路由参数中获取价格和数量，并设置到响应式引用和表单中 
    price.value = Number(route.query.price);
    count.value = Number(route.query.count);
    ruleForm.count = count.value
})

// 提交表单函数
const submitForm = () => {
    if (cstatus.value === 0) {
        // 填充表单数据
        ruleForm.note = note.value;
        ruleForm.payment_method = payment.value!;
        ruleForm.store = takeout.value?.store!;
        ruleForm.count = count.value!;
        ruleForm.address = address.value?.id!;
        ruleForm.takeout = takeout.value?.id!;
        ruleForm.price = price.value!;
        orderApis.submitOrder(ruleForm)
            .then((value: OrderModel) => {
                if (value) {
                    ElMessage.success('订单提交成功，请尽快支付');
                    status.value = `立即支付¥ (${price.value})`;
                    cstatus.value = 1;
                    order.value = value;
                    // 如果是从菜单进入的，则删除菜单项
                    if (Number(route.query.way) == 1) {
                        menuApis.deleteMenu(Number(route.query.menu), userStore.id)
                    }
                }
            })
    } else {// 如果是已提交待支付的订单，则进行支付  
        // 更新订单 
        orderApis.updateOrder(order.value?.id!)
            .then((value: OrderModel) => {
                if (value) {
                    // 发起支付请求
                    let payment: PaymentModel = {
                        price: order.value!.price,
                        user: order.value!.user,
                        store: order.value!.store,
                        order: order.value!.id!
                    }
                    paymentApis.paymentOrder(payment)
                        .then((result: boolean) => {
                            if (result) {
                                ElMessage.success("支付成功")
                                router.back()// 返回上一页
                            } else {
                                ElMessage.error("支付失败")
                            }
                        })
                }
            })
    }
}
</script>
